package com.kcl.dfss.utils;

import java.lang.reflect.Method;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;



public class WiFiManagerUtils {
	
	private static WifiManager wifiManager;
	
	//初始化
	public static void  initWifiManager(Context context){
		wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
	}
	
	//获取WiFi的名字
	public static String getWiFiName(Context context){
		
		initWifiManager(context);
		if(wifiManager != null){
			WifiInfo info = wifiManager.getConnectionInfo();
			if(info != null){
				return info.getSSID();
			}
		}
		return null;
	}
	
	//判断热点开启状态
	public static boolean isWifiApEnabled(Context context){
		return getWifiApState(context) == WIFI_AP_STATE.WIFI_AP_STATE_ENABLED;
	}
	
	private static WIFI_AP_STATE getWifiApState(Context context){
		int tmp;
		initWifiManager(context);
		try {
			Method method = wifiManager.getClass().getMethod("getWifiApState");
			tmp = ((Integer) method.invoke(wifiManager));
			// Fix for Android 4
			if (tmp > 10) {
				tmp = tmp - 10;
			}
			return WIFI_AP_STATE.class.getEnumConstants()[tmp];
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return WIFI_AP_STATE.WIFI_AP_STATE_FAILED;
		}
	}
	
	//热点的状态枚举
	public enum WIFI_AP_STATE {
		WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_ENABLING,  WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_FAILED
	}
	
	/**
	 * wifi热点开关      
	 * @param enabled	true：打开	 false：关闭
	 * @return	true：成功	 false：失败
	 * @WiFiAP_NAME	热点的名称
	 * @WiFiAP_PWD  热点的密码
	 */
	public static boolean setWifiApEnabled(Context context,boolean enabled,String WiFiAP_NAME,String WiFiAP_PWD) {
		initWifiManager(context);
		if (enabled) { // disable WiFi in any case
			//wifi和热点不能同时打开，所以打开热点的时候需要关闭wifi
			wifiManager.setWifiEnabled(false);
		}else{
			wifiManager.setWifiEnabled(true);
		}
		try {
			//热点的配置类
			WifiConfiguration apConfig = new WifiConfiguration();
			//配置热点的名称(可以在名字后面加点随机数什么的)
			apConfig.SSID = WiFiAP_NAME;
			//配置热点的密码
			apConfig.preSharedKey = WiFiAP_PWD;
			//安全：WPA2_PSK
			apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
			//通过反射调用设置热点
			Method method = wifiManager.getClass().getMethod(
					"setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
			//返回热点打开状态
			boolean state = (Boolean) method.invoke(wifiManager, apConfig, enabled);
			/*if(state){
				Message message = new Message();
				message.what = 1;
				handler.sendMessage(message);
			}*/
			return state;
		} catch (Exception e) {
			return false;
		}
	}
}
